package com.coocare.licence.config.i18n;


import cn.hutool.core.util.StrUtil;
import com.coocare.licence.config.CommonConstants;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Locale;

/**
 * RequestContextFilter 会传入默认的Locale，优先级(-105) 要比RequestContextFilter优先级高
 */
@Slf4j
@Component
@Order(-104)
public class LocaleChangeFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String newLocale = request.getHeader("locale");

        LocaleContextHolder.setLocale(getLocal(newLocale));
        filterChain.doFilter(request, response);
    }

    private static Locale getLocal(String langStr) {
        if (langStr == null) {
            return getDefaultLocal();
        }

        if (!StrUtil.contains(langStr, CommonConstants.UNDERLINE)) {
            return new Locale(langStr);
        }
        String[] s = langStr.split(CommonConstants.UNDERLINE);
        if (s.length > 1) {
            return new Locale(s[0], s[1]);
        }
        // 数组长度不够代表前端传的语言编码格式有问题，但这里不能报错，所以要判断下长度>1，否则一旦格式出现问题，所有接口都无法使用
        // 改为使用默认语言
        return getDefaultLocal();
    }


    private static Locale getDefaultLocal() {
        String langStr = CommonConstants.DEFAULT_LANG.getLanguage();
        if (!StrUtil.contains(langStr, CommonConstants.UNDERLINE)) {
            return new Locale(langStr);
        }
        // 默认语言就没必要判断数组长度了，如果长度不够代表语言编码的格式有问题，就算能运行也是个bug
        String[] s = CommonConstants.DEFAULT_LANG.getLanguage().split(CommonConstants.UNDERLINE);
        return new Locale(s[0], s[1]);
    }
}
